package srzy.socket

import java.net._
import java.util.concurrent.locks.ReentrantLock
import java.io.IOException
import srzy.common.Logging
import srzy.common.Config

abstract class SocketServerConn extends Logging {

  val serverSocket: ServerSocket
  val pro: Protocol

  def accept() = {
    logger.debug("accept socket start")
    var flag = true
    var s: java.net.Socket = null
    var i = 0
    while (s == null) {
      try {
        s = serverSocket.accept()
      } catch {
        case ste: SocketTimeoutException =>
          i = i + 1
          if (i <= 5) {
            logger.debug("socket accept wait " + (i * 2) + "s")
          } else {
            logger.error("socket accept time out"); throw ste
          }
        case e: Exception =>
          logger.error("accept socket failed", e)
          throw e
      }
    }
    s
  }

  def close() = {
    logger.info("Close SocketServerConn start!")
    try {
      serverSocket.close()
    } catch {
      case e: Exception => logger.error("Close the server failed !", e)
    }
    logger.info("Close SocketServerConn over!")
  }
}

object SocketServerConn extends Logging {

  def create(port: Int): ServerSocket = {
    try {
      val s = new ServerSocket(port)
      s.setSoTimeout(2000)
      s.setReceiveBufferSize(32 * 1024)
      logger.info("Established server at " + port + " success!")
      s
    } catch {
      //      case ste: java.net.SocketTimeoutException =>
      //        logger.error("wait for socket to connect")
      //        throw ste
      case e: Exception =>
        logger.error("Established server at " + port + " failure!", e)
        throw e
    }
  }
}